#! /usr/bin/python
# -*- coding: cp1250 -*-

import os
import glob
import time
import checksums

# todos:
## should test on gnulinux
## should include doctests
## consider using class

def dfstats(pathmask, options=['atime', 'ctime', 'sha1', 'sha256', 'md5'], pprint=False):

    # to speed up processing some options can be ommited (explicitly)
    o = options

    res = {}

    for file in glob.glob(pathmask):
    
        print file
        
        res[file] = {}

        # retrieves the stats for the current file as a tuple
        # (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)
        # the tuple element mtime at index 8 is the last-modified-date
        stats = os.stat(file)

        # file size
        res[file]['size'] = stats[6]
        # file name
        res[file]['folder'], res[file]['file_name'] = os.path.split(file)

        # create tuple (year yyyy, month(1-12), day(1-31), hour(0-23), minute(0-59), second(0-59),
        # weekday(0-6, 0 is monday), Julian day(1-366), daylight flag(-1,0 or 1)) from seconds since epoch
        # note:  this tuple can be sorted properly by date and time
        if 'atime' in o: res[file]['atime'] = time.localtime(stats[7])
        res[file]['mtime'] = time.localtime(stats[8])
        if 'ctime' in o: res[file]['ctime'] = time.localtime(stats[9])
        
        # convert date tuple to YYYY-MM-DDTHH:MM:SS format
        if 'atime' in o: res[file]['atime_iso'] = time.strftime("%Y-%m-%dT%H:%M:%S", res[file]['atime'])
        res[file]['mtime_iso'] = time.strftime("%Y-%m-%dT%H:%M:%S", res[file]['mtime'])
        res[file]['mtime_plain'] = time.strftime("%Y%m%d%H%M%S", res[file]['mtime'])
        if 'ctime' in o: res[file]['ctime_iso'] = time.strftime("%Y-%m-%dT%H:%M:%S", res[file]['ctime'])

        if 'md5' in o: res[file]['md5'] = checksums.chs_md5(file)
        if 'sha1' in o: res[file]['sha1'] = checksums.chs_sha1(file)
        if 'sha256' in o: res[file]['sha256'] = checksums.chs_sha256(file)

    if pprint:
        for f in sorted(res.keys()):
            print f
            for s in sorted(res[f]):
                print ' '*10,'%-15s : %s' % (s, res[f][s])

    return res        

if __name__ == '__main__':
    #fs = dfstats(r'c:\*.ini', options=['sha1'], pprint=True)
    #fs = dfstats(r'c:\*.ini', options=['sha1'])
    #fs = dfstats(r'c:\*.ini')

    #fs = dfstats(r'c:\aft\*.*', options=['sha1'], pprint=True)
    #fs = dfstats(r'c:\aft\*.*', options=['sha1', 'sha256'], pprint=True)
    fs = dfstats(r'c:\aft\test\*.*', options=['atime'], pprint=True)
    
    print fs